package org.kjtc.socket;

import java.util.Date;

import org.kjtc.util.Tools;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf byteBuf = (ByteBuf)msg;
        // 获取缓冲区可读的字节数
        byte[] request = new byte[byteBuf.readableBytes()];
        byte[] back = new byte[18];
        byteBuf.readBytes(request);

        System.out.println("netty服务器接收数据：" + Bytes2HexString(request));
    	for(int i = 0; i < 9; i++) {
    		back[i] = request[i];
    	}
    	back[9] = (byte) 0x06;
    	String date = Tools.date2Str(new Date(), "yyyyMMddHHmmss");
    	back[10] = (byte) Integer.parseInt(date.substring(2, 4), 16);
    	back[11] = (byte) Integer.parseInt(date.substring(4, 6), 16);
    	back[12] = (byte) Integer.parseInt(date.substring(6, 8), 16);
    	back[13] = (byte) Integer.parseInt(date.substring(8, 10), 16);
    	back[14] = (byte) Integer.parseInt(date.substring(10, 12), 16);
    	back[15] = (byte) Integer.parseInt(date.substring(12, 14), 16);

    	int checkNum = 0;
    	for(int i = 0; i < 16; i++) {
    		checkNum += back[i];
    	}
    	back[16] = (byte) checkNum;
    	back[17] = (byte) 0x16;
        //  把带发送的消息放到缓存数组中，再通过flush将发送的缓冲区的消息全部写到SocketChannel中
        ByteBuf response = Unpooled.copiedBuffer(back);
        // 异步发送应答消息给客户端
        ctx.write(response);
	}
	
	public static String Bytes2HexString(byte[] b) {
        String ret = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            ret += hex.toUpperCase();
        }
        return ret;
    }
	
	@Override
    public void channelReadComplete (ChannelHandlerContext ctx) throws Exception {
        // 将消息发送队列中的消息写入到SocketChannel中发送给对方
        ctx.flush();
    }

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}
}